package org.example.algorithm.linkedlist;

public class ReverseBetween {

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        ListNode cur = node1;
        while (cur != null) {
            System.out.println("打印节点" + cur.val);
            cur = cur.next;
        }
        System.out.println("执行翻转");
        ListNode res = reverseBetween(node1, 1, 5);
        cur = res;
        while (cur != null) {
            System.out.println("打印节点" + cur.val);
            cur = cur.next;
        }
    }

    public static ListNode reverseBetween(ListNode head, int left, int right) {
        ListNode newCur = null;
        ListNode cur = head;
        ListNode reversePart = null;
        ListNode leftPointer = null;
        int i = 1;
        while (cur != null && i <= right) {
            if (i < left) {
                newCur = cur;
                cur = cur.next;
                i++;
                continue;
            }
            if (i == left) {
                leftPointer = cur;
            }
            ListNode temp = cur.next;
            cur.next = reversePart;
            reversePart = cur;
            cur = temp;
            i++;
        }
        if (newCur != null) {
            newCur.next = reversePart;
        } else {
            head = reversePart;
        }
        leftPointer.next = cur;
        return head;
    }
}
